<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars fixed" :isLeft="true">
      <template #title><text>生日祝福</text></template>
    </GlobalTopBar>
    <GlobalTopBar ref="topBarRef"> </GlobalTopBar>
    <view class="page_content">
      <image
        class="zf_img"
        :src="`${store.imgDomain}zf_img.jpg`"
        mode="widthFix"
      />
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { useCounterStore } from '@/store';
import { onLaunch, onShow, onUnload } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { validatePhone } from '@/utils/validate';

const store = useCounterStore();
const userInfo = ref({});

// 参数
const fromDttas = reactive({
  id: '',
  contact_name: '',
  phone: '',
  region_name: '',
  province_name: '',
  city_name: '',
  district_name: '',
  address: '',
  longitude: '',
  latitude: '',
  is_default: 0,
});
//
const ulList = computed(() => [
  {
    text: '姓名',
    value: fromDttas.contact_name,
    placeholder: '请输入姓名',
    key: 'contact_name',
  },
  {
    text: '手机号',
    value: fromDttas.phone,
    placeholder: '请输入手机号',
    key: 'phone',
    maxlength: 11,
    type: 'number',
  },
  {
    text: '地区',
    value: `${
      fromDttas.province_name + fromDttas.city_name + fromDttas.district_name
    }`,
    placeholder: '请选择省市区县',
  },
  {
    text: '详细地址',
    value: fromDttas.address,
    key: 'address',
    placeholder: '小区、街道、写字楼',
  },
]);

// 输入框改变触发
const changeFun = (val, key) => {
  console.log(val, key);
  fromDttas[key] = val.detail.value;
};

// 存储选择的位置信息
const selectedLocation = ref(null);

// 调起微信原生地图选择页面（自带搜索功能）
const openNativeMap = () => {
  // 检查位置权限（可选，提升体验）
  uni.getSetting({
    success: (settingRes) => {
      console.log('settingRes', settingRes);

      // 若未授权位置权限，先申请授权
      if (!settingRes.authSetting['scope.userLocation']) {
        uni.authorize({
          scope: 'scope.userLocation',
          success: (res) => {
            launchMap(); // 授权成功后调起地图
          },
          fail: () => {
            // 引导用户到设置页开启权限
            uni.showModal({
              title: '权限申请',
              content: '需要获取您的位置以显示附近地点，请开启位置权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting(); // 打开小程序设置页
                }
              },
            });
          },
        });
      } else {
        launchMap(); // 已授权，直接调起地图
      }
    },
  });
};

// 核心：调用 uni.chooseLocation 调起原生地图
const launchMap = () => {
  uni.chooseLocation({
    // 可选：设置地图初始中心位置（经纬度）
    // latitude: 39.9042, // 示例：北京纬度
    // longitude: 116.4074, // 示例：北京经度
    success: (res) => {
      getTencentMapAddress(res.latitude, res.longitude, res.name);
    },
    fail: (err) => {
      // 处理失败（如用户取消选择）
      if (err.errMsg !== 'chooseLocation:fail cancel') {
        uni.showToast({
          title: '地图选择失败',
          icon: 'none',
        });
      }
    },
  });
};

// 【腾讯地图】经纬度获取地信息
const getTencentMapAddress = async (latitude, longitude, name) => {
  const data = await request('wxapp/common/getTencentMapAddress', {
    location: `${latitude},${longitude}`,
  });
  fromDttas.longitude = longitude;
  fromDttas.latitude = latitude;
  fromDttas.province_name = data.ad_info.province;
  fromDttas.city_name = data.ad_info.city;
  fromDttas.district_name = data.ad_info.district;
  fromDttas.region_name = name;
  fromDttas.address = fromDttas.address ? fromDttas.address : name;
};

// 保存会员服务地址数据
const doSaveUserAddress = async () => {
  console.log(fromDttas);

  if (!fromDttas.contact_name) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    });
    return;
  } else if (!validatePhone(fromDttas.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.province_name) {
    uni.showToast({
      title: '请选择地区',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.address) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none',
    });
    return;
  }
  const data = await request(
    'wxapp/user/doSaveUserAddress',
    {
      ...fromDttas,
    },
    'POST',
  );
  uni.navigateBack({
    delta: 1,
  });
};
uni.$on('datas', (data) => {
  fromDttas.id = data.id;
  fromDttas.is_default = data.is_default;
  for (let key in fromDttas) {
    fromDttas[key] = data[key];
  }
});
onLaunch(() => {});
onUnload(() => {
  uni.$off('datas');
});
</script>

<style lang="scss" scoped>
.topbars {
  background-color: #ffffff;
}
.page-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
.page_content {
  background-color: #227ee9;
  .zf_img {
    width: 750rpx;
  }
}
</style>
